package cn.miao.photoprinter.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.entity.PhotoCheckItem;

import com.nostra13.universalimageloader.core.ImageLoader;

public class MyImageAdapter extends BaseAdapter {

    private LayoutInflater infalter;
    private ArrayList<PhotoCheckItem> photoCheckItems = new ArrayList<PhotoCheckItem>();

    public MyImageAdapter(Context context) {
        infalter = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return photoCheckItems.size();
    }

    @Override
    public PhotoCheckItem getItem(int position) {
        return photoCheckItems.get(position);
    }
    
    public String getCheckedItems() {
    	String rtStr = "";
    	for (PhotoCheckItem item : photoCheckItems) {
    		if (item.isCheck()) {
    			rtStr += "," + item.getPath();
    		}
    	}
    	return rtStr.length() > 1 ? rtStr.substring(1) : rtStr;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addAll(ArrayList<PhotoCheckItem> photoCheckItems) {
        this.photoCheckItems.clear();
        this.photoCheckItems.addAll(photoCheckItems);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = infalter.inflate(R.layout.item_image, parent, false);
            holder = new ViewHolder();
            holder.iv_item = (ImageView) convertView.findViewById(R.id.iv_item);
            holder.ck_item = (CheckBox) convertView.findViewById(R.id.ck_item);
            holder.tv_path = (TextView) convertView.findViewById(R.id.tv_path);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
            resetViewCache(holder);
        }
        if (position > photoCheckItems.size() - 1) {
        	position = photoCheckItems.size() - 1;
        }
        PhotoCheckItem item = photoCheckItems.get(position);
        holder.tv_path.setText(item.getPath());
        ImageLoader.getInstance().displayImage("file://" + item.getPath(), holder.iv_item);
        holder.ck_item.setChecked(item.isCheck());
        return convertView;
    }
    
    private void resetViewCache(ViewHolder viewcache){  
        viewcache.tv_path.setText(null);  
        viewcache.ck_item.setChecked(false);
        viewcache.iv_item.setImageDrawable(null);
    }

    class ViewHolder {
        ImageView iv_item;
        CheckBox ck_item;
        TextView tv_path;
    }

}
